package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.service.ArticleViewHistoryService;
import com.zja.service.Impl.ArticleViewHistoryServiceImpl;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
 * @author JA
 * @date: 2025/5/7
 * description:删除单条浏览记录
 */
@WebServlet("/api/viewHistory/delete")
public class DeleteSingleViewHistoryServlet extends HttpServlet {
    private final ArticleViewHistoryService viewHistoryService = new ArticleViewHistoryServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idStr = req.getParameter("id");
        if (idStr == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("缺少参数：id"));
            return;
        }

        Long recordId = Long.valueOf(idStr);
        HttpSession session = req.getSession(false);
        Long authorId = (session != null) ? (Long) session.getAttribute("userId") : null;

        if (authorId == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("未登录，无法删除记录"));
            return;
        }

        boolean success = viewHistoryService.deleteViewRecordById(recordId, authorId);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("删除成功"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("删除失败或权限不足"));
        }
    }
}
